﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
public partial class Manage_basisset_GroupUsers : AdminPageBase
{
    int id;
    protected void Page_Load(object sender, EventArgs e)
    {
        CheckAdmin();
        GetUserPermisions();
        GetGroupId();
        if (!IsPostBack)
        {
            // 正确的属性设置方法
            this.GridView1.Attributes.Add("SortExpression", "UserId");
            this.GridView1.Attributes.Add("SortDirection", "ASC");
            this.GridView2.Attributes.Add("SortExpression", "UserId");
            this.GridView2.Attributes.Add("SortDirection", "ASC");
            DataTable dt = new DataTable();
            dt.Columns.Add("UserId");
           
            dt.Columns.Add("Code");
           
            dt.Columns.Add("Name");
           
            dt.Columns.Add("");
            GridviewControl.GridViewDataBind(this.GridView2, dt);
            GridviewControl.ResetGridView(this.GridView2);
            BindGroupUser();
           
           // BindSelectUser();
        }
    }
    protected void GetGroupId()
    {
        if (Request.QueryString["id"] == null)
        {
            id = 0;

        }
        else
        {
            id = Convert.ToInt32(Request.QueryString["id"]);

        }
    }
    protected void CheckAdmin()
    {
        if (AdminSessionHelper.UserDetails == null)
        {
            JsHelper.TopAlertRedirect("请先登录", "../login.aspx", this.Page);
        }
    }
    protected void BindGroupUser()
    {
        if (id != 0)
        {
            // 获取GridView排序数据列及排序方向
            string sortExpression = this.GridView1.Attributes["SortExpression"];
            string sortDirection = this.GridView1.Attributes["SortDirection"];
            ibtnsearch.Enabled = true;
            DataSet ds = jtDataAccess.GetGroupUser(id);
            if (CoreTools.CheckDataSet(ds))
            {
                // 根据GridView排序数据列及排序方向设置显示的默认数据视图
                if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                {
                    ds.Tables[0].DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                }

                // GridView绑定并显示数据
                //this.GridView1.DataSource = ds.Tables[1];
                // this.GridView1.DataBind();
                GridviewControl.GridViewDataBind(this.GridView1, ds.Tables[0]);
                btnexport.Visible = true;
                Button1.Enabled = true;
                selectAll1.Enabled = true;
                ibtnsearch.Enabled = true;
            }
            else
            {
                // this.GridView1.DataSource = null;
                // this.GridView1.DataBind();
                DataTable dt = new DataTable();
                dt.Columns.Add("UserId");
                dt.Columns.Add("Code");
                
                dt.Columns.Add("Name");
               
                dt.Columns.Add("IsValid");

                dt.Columns.Add("");
                GridviewControl.GridViewDataBind(this.GridView1, dt);
                GridviewControl.ResetGridView(this.GridView1);
                btnexport.Visible = false;
                Button1.Enabled = false;
                selectAll1.Enabled = false;

            }


        }
        else
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("UserId");
            dt.Columns.Add("Code");
           
            dt.Columns.Add("Name");
           
            dt.Columns.Add("IsValid");

            dt.Columns.Add("");
            GridviewControl.GridViewDataBind(this.GridView1, dt);
            btnexport.Visible = false;
            Button1.Enabled = false;
            selectAll1.Enabled = false;
            ibtnsearch.Enabled = false;
        }
    }
    protected void BindSelectUser()
    {
       
        string keyword = txtkeyword.Text.Trim();
        if (!CoreTools.ProcessSqlStr(keyword, 0))
        {
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert(ConfigHelper.ProcessSqlStrErroMsg), false);
        }
        else
        {
            // 获取GridView排序数据列及排序方向
            string sortExpression = this.GridView2.Attributes["SortExpression"];
            string sortDirection = this.GridView2.Attributes["SortDirection"];
            DataSet ds = jtDataAccess.FilterUser(keyword);
            if (CoreTools.CheckDataSet(ds))
            {
                // 根据GridView排序数据列及排序方向设置显示的默认数据视图
                if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                {
                    ds.Tables[0].DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                }

                // GridView绑定并显示数据
                //this.GridView2.DataSource = ds.Tables[0];
                //this.GridView2.DataBind();
                // pager1.RecordCount = Convert.ToInt32(ds.Tables[1].Rows[0]["Total"]);
                GridviewControl.GridViewDataBind(this.GridView2, ds.Tables[0]);
             
                    btnDeleteAdd.Enabled = true;
                    ibtnsearch.Enabled = true;
                    selectAll.Enabled = true;
            }
            
            else
            {
                // this.GridView2.DataSource = null;
                // this.GridView2.DataBind();
                // pager1.RecordCount = 0;
                DataTable dt = new DataTable();
                dt.Columns.Add("UserId");
               
                dt.Columns.Add("Code");
               
                dt.Columns.Add("Name");
              

                dt.Columns.Add("");
                GridviewControl.GridViewDataBind(this.GridView2, dt);
                GridviewControl.ResetGridView(this.GridView2);
                btnDeleteAdd.Enabled = false;
                selectAll.Enabled = false;

            }
        }
        GridviewControl.ResetGridView(this.GridView1);
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //首先判断是否是数据行
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //当鼠标停留时更改背景色
            e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FCFDEE'");
            //当鼠标移开时还原背景色
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            e.Row.Cells[1].Attributes.Add("class", "text");
        }


    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        // 从事件参数获取排序数据列
        string sortExpression = e.SortExpression.ToString();

        // 假定为排序方向为“顺序”
        string sortDirection = "ASC";

        // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
        if (sortExpression == this.GridView1.Attributes["SortExpression"])
        {
            //获得下一次的排序状态
            sortDirection = (this.GridView1.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
        }

        // 重新设定GridView排序数据列及排序方向
        this.GridView1.Attributes["SortExpression"] = sortExpression;
        this.GridView1.Attributes["SortDirection"] = sortDirection;

        this.BindGroupUser();
        GridviewControl.ResetGridView(this.GridView2);
    }
    protected void btnexport_Click(object sender, EventArgs e)
    {
       // DataTable dt = GetExportData();
       // ExcelExport(GetStringWriter(dt), "用户组用户成员.xls");
        DataTable dt = GetExportData();
        if (dt.Rows.Count == 0)
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("没有数据，不需要导出吧！"), false);
        else
        {
            string style = @"<style> .text { mso-number-format:\@;color:#000000 } </style> ";

            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.Charset = "GB2312";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("用户组用户成员.xls", System.Text.Encoding.GetEncoding("utf-8")));
            HttpContext.Current.Response.ContentType = "application/ms-excel";

            StringWriter sw = new StringWriter();

            HtmlTextWriter htw = new HtmlTextWriter(sw);
            GridView1.Columns[4].Visible = false;
            GridView1.Columns[0].Visible = false;
            GridView1.AllowPaging = false;
            GridView1.AllowSorting = false;
            GridView1.DataSource = dt;
            GridView1.DataBind();
            GridView1.RenderControl(htw);

            // Style is added dynamically
            Response.Write(style);

            Response.Write(sw.ToString());

            Response.End();
        }


        GridviewControl.ResetGridView(this.GridView2);
    }
    public override void VerifyRenderingInServerForm(Control control)
    {

    }
    protected DataTable GetExportData()
    {
        DataTable dt = new DataTable();
        // 获取GridView排序数据列及排序方向
        string sortExpression = this.GridView1.Attributes["SortExpression"];
        string sortDirection = this.GridView1.Attributes["SortDirection"];
        DataSet ds = jtDataAccess.GetGroupUser(id);
        if (CoreTools.CheckDataSet(ds))
        {
            // 根据GridView排序数据列及排序方向设置显示的默认数据视图
            if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
            {
                ds.Tables[0].DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
            }

            dt = ds.Tables[0];

        }
        return dt;

    }
    protected void ExcelExport(StringWriter sw, string exportFileName)
    {

        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.Charset = "GB2312";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(exportFileName, System.Text.Encoding.GetEncoding("utf-8")));
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        // HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\" />");
        HttpContext.Current.Response.Write(sw.ToString());
        HttpContext.Current.Response.End();


    }
    //将datatable中的数据进行组装，比如添加列头（这样excel文件中第一行就看到列头名称） 
    public static StringWriter GetStringWriter(DataTable dt)
    {
        StringWriter sw = new StringWriter();

        //先写列的表头，这样保证如果没有数据也能输出列表头 
        sw.Write("用户帐号" + "\t ");
        sw.Write("用户姓名" + "\t ");
        sw.Write("用户状态" + "\t ");
     
        sw.Write(sw.NewLine);

        //如果包含数据 
        if (dt != null)
        {
            //写数据 
            foreach (DataRow dr in dt.Rows)
            {
                sw.Write(dr["Code"].ToString() + "\t ");
                sw.Write(dr["Name"].ToString() + "\t ");
                sw.Write(dr["IsValid"].ToString() + "\t ");
              
                //换行 
                sw.Write(sw.NewLine);
            }
        }
        sw.Close();
        return sw;
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Del")
        {
            UserType ut = new UserType();//用户自定义类型
            DataTable  userTable = ut.GetUserTableType();

            DataRow UserRow;

            UserRow = userTable.NewRow();
            UserRow["UserId"] = e.CommandArgument.ToString();
            userTable.Rows.Add(UserRow);
            userTable.AcceptChanges();
            int flag = jtDataAccess.OpUserGroup(JTDataAccess.OpType.Delete,id, userTable);

            switch (flag)
            {
                case 0:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("删除失败！"), false);
                    break;

                case 1:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("删除成功！"), false);
                    this.BindGroupUser();
                    break;

                default:
                    break;
            }

        }
        GridviewControl.ResetGridView(this.GridView2);
    }

    protected void btnDeleteAdd_Click(object sender, EventArgs e)
    {
        if (id == 0)
        {
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("必须先保存组别名称和备注信息！"), false);
        }
        else
        {
            UserType ut = new UserType();//用户自定义类型
            DataTable userTable = ut.GetUserTableType();

            DataRow UserRow;
            for (int i = 0; i <= GridView2.Rows.Count - 1; i++)
            {
                CheckBox cbox = (CheckBox)GridView2.Rows[i].FindControl("chkID");
                HiddenField hdfUserId = (HiddenField)GridView2.Rows[i].FindControl("hdfUserId");
                if (cbox.Checked == true && hdfUserId != null && hdfUserId.Value != "")
                {

                    UserRow = userTable.NewRow();
                    UserRow["UserId"] = hdfUserId.Value;
                    userTable.Rows.Add(UserRow);
                }
            }
            userTable.AcceptChanges();
            int flag = jtDataAccess.OpUserGroup(JTDataAccess.OpType.Insert, id, userTable);

            switch (flag)
            {
                case 0:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("添加失败！"), false);
                    break;

                default:
                     ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("添加成功！"), false);
                    this.BindGroupUser();
                    this.BindSelectUser();
                    break;
            }
            selectAll.Checked = false;
        }
        GridviewControl.ResetGridView(this.GridView1);
    }
    protected void selectAll_CheckedChanged(object sender, EventArgs e)
    {
        for (int i = 0; i <= GridView2.Rows.Count - 1; i++)
        {
            CheckBox cbox = (CheckBox)GridView2.Rows[i].FindControl("chkID");
            if (selectAll.Checked == true)
            {
                cbox.Checked = true;
            }
            else
            {
                cbox.Checked = false;
            }
        }
        GridviewControl.ResetGridView(this.GridView1);
    }
    protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        //首先判断是否是数据行
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //当鼠标停留时更改背景色
            e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FCFDEE'");
            //当鼠标移开时还原背景色
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");

        }
    }
    protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
    {
        // 从事件参数获取排序数据列
        string sortExpression = e.SortExpression.ToString();

        // 假定为排序方向为“顺序”
        string sortDirection = "ASC";

        // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
        if (sortExpression == this.GridView2.Attributes["SortExpression"])
        {
            //获得下一次的排序状态
            sortDirection = (this.GridView2.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
        }

        // 重新设定GridView排序数据列及排序方向
        this.GridView2.Attributes["SortExpression"] = sortExpression;
        this.GridView2.Attributes["SortDirection"] = sortDirection;

        this.BindSelectUser();
        GridviewControl.ResetGridView(this.GridView1);

    }
    protected void pager1_PageChanged(object sender, EventArgs e)
    {
        // this.BindSelectClass();
    }
    protected void ibtnsearch_Click(object sender, ImageClickEventArgs e)
    {
        BindSelectUser();
    }
    protected void selectAll1_CheckedChanged(object sender, EventArgs e)
    {
        for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
        {
            CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("chkID1");
            if (selectAll1.Checked == true)
            {
                cbox.Checked = true;
            }
            else
            {
                cbox.Checked = false;
            }
        }
        GridviewControl.ResetGridView(this.GridView2);
    }
    protected void btnDeleteMass_Click(object sender, EventArgs e)
    {
        UserType ut = new UserType();//用户自定义类型
        DataTable UserTable = ut.GetUserTableType();

        DataRow UserRow;
        for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
        {
            CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("chkID1");
            HiddenField hdfUserId = (HiddenField)GridView1.Rows[i].FindControl("hdfUserId");
            if (cbox.Checked == true && hdfUserId != null && hdfUserId.Value != "")
            {

                UserRow = UserTable.NewRow();
                UserRow["UserId"] = hdfUserId.Value;
                UserTable.Rows.Add(UserRow);
            }
        }
        UserTable.AcceptChanges();
        int flag = jtDataAccess.OpUserGroup(JTDataAccess.OpType.Delete,id, UserTable);

        switch (flag)
        {
            case 0:
                ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("删除失败！"), false);
                break;

            default:
                ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("删除成功！"), false);
                this.BindGroupUser();
                break;
        }
        selectAll1.Checked = false;
        GridviewControl.ResetGridView(this.GridView2);
    }
}